package tech.dnf.demo.rabbitmq;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Producer {
    private static Connection conn = null;
    private static Channel channel = null;
    private static ExecutorService executorService = null;

    private static final String PTPQ = "ptpq_1";

    public static void main(String[] args) throws Exception {
        init();

        ptpqTest();

        close();
    }

    private static void init() throws Exception {
        conn = ConnectionUtil.getConnection();
        channel = conn.createChannel();

        channel.queueDeclare(PTPQ, false, false, false, null);


        executorService = Executors.newCachedThreadPool();
    }

    private static void close() throws Exception {
        if (null != executorService) {
//            executorService.
            executorService.shutdown();
            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        }

        if (null != channel) {
            channel.close();
            channel = null;
        }
        if (null != conn) {
            conn.close();
            conn = null;
        }
    }

    public static void ptpqTest() throws IOException {
        executorService.submit(() -> {
            String msg = "Hello rabbit mq";
            int i = 0;
            try {
                while (i++ <= 127) {
                    Thread.sleep(100);
                    String b = msg + i;
                    channel.basicPublish("", PTPQ, null, b.getBytes());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
